﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Views;
using JiveMessenger.Models;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using JmShared;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Contacts;
namespace JiveMessenger.ViewModels
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class ViewModelAddContact : ViewModelBaseEx
    {
        private IClient _currentClient;
        private INavigationService _navigationService;
        private bool _isBusy;
        public RelayCommand AddContactCommand { get; set; }

        private ObservableCollection<string> _autoSuggestItems;
        public ObservableCollection<string> AutoSuggestItems
        {
            get { return _autoSuggestItems; }
            set
            {
                if (_autoSuggestItems != value)
                {
                    Set(() => AutoSuggestItems, ref _autoSuggestItems, value);
                }
            }
        }


        private bool _success;
        public bool Success
        {
            get { return _success; }
            set
            {
                if (_success != value)
                {
                    Set(() => Success, ref _success, value);
                }
            }
        }

        private string _inputText;
        public string InputText
        {
            get { return _inputText; }
            set
            {
                if (_inputText != value)
                {
                    Set(() => InputText, ref _inputText, value.Trim());
                    AddContactCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private string _statusText;
        public string StatusText
        {
            get { return _statusText; }
            set
            {
                if (_statusText != value)
                {
                    Set(() => StatusText, ref _statusText, value);
                }
            }
        }
        private string _nextButtonText;
        public string NextButtonText
        {
            get { return _nextButtonText; }
            set
            {
                if (_nextButtonText != value)
                {
                    Set(() => NextButtonText, ref _nextButtonText, value);
                }
            }
        }

        private bool _isInputTextboxEnabled;
        public bool IsInputTextboxEnabled
        {
            get { return _isInputTextboxEnabled; }
            set
            {
                if (_isInputTextboxEnabled != value)
                {
                    Set(() => IsInputTextboxEnabled, ref _isInputTextboxEnabled, value);
                }
            }
        }

        private string _messageToReceiverText;
        public string MessageToReceiverText
        {
            get { return _messageToReceiverText; }
            set
            {
                if (_messageToReceiverText != value)
                {
                    Set(() => MessageToReceiverText, ref _messageToReceiverText, value);
                }
            }
        }


        /// <summary>
        /// Initializes a new instance of the ViewModelAddContact class.
        /// </summary>
        public ViewModelAddContact(IClient currentClient, INavigationService navService)
        {
            _navigationService = navService;
            _currentClient = currentClient;
            NextButtonText = "Next";
            IsInputTextboxEnabled = true;
            if (IsInDesignMode)
            {
                StatusText = "this is the status text of your add member query!";
                return;
            }
            AddContactCommand = new RelayCommand(AddContactCommandAction, () => !String.IsNullOrEmpty(InputText) && StaticMethods.IsValidEmail(InputText) && !_isBusy);

            SetAutosuggestItems();

        }

        private async void SetAutosuggestItems()
        {

            IEnumerable<IContact> jiveContacts = new List<IContact>();
            Messenger.Default.Send(new NotificationMessageAction<IEnumerable<IContact>>(this, ViewModelContactList.MessengerCommands.GetContacts.ToString(), contacts =>
            {
                if (contacts != null)
                    jiveContacts = contacts;

            }));
            List<string> suggestItems = new List<string>();
            suggestItems.AddRange(jiveContacts.Where(x => !x.IsFriend && _currentClient.CurrentUserInfo.UserName != x.UserName).Select(x => x.UserName).Distinct().ToList());
#if WINDOWS_PHONE_APP
            var contactStore = await ContactManager.RequestStoreAsync();
            var phoneContacts = await contactStore.FindContactsAsync();
            phoneContacts = phoneContacts.Where(phoneContact => phoneContact.Emails.Count > 0 && !jiveContacts.Any(jiveContact => jiveContact.IsFriend && phoneContact.Emails.Any(email => email.Address == jiveContact.UserName))).ToList();
            var phoneContactStrings = phoneContacts.Select(x => x.Emails.First().Address).Distinct().ToList();
            suggestItems.AddRange(phoneContactStrings);
#endif
            AutoSuggestItems = new ObservableCollection<string>(suggestItems);
        }


        public override void Cleanup()
        {
            base.Cleanup();
            SimpleIoc.Default.Unregister<ViewModelAddContact>(VmHelper.Locator.ViewModelAddContactKey);
            VmHelper.Locator.ViewModelAddContactKey = System.Guid.NewGuid().ToString();
        }
        private async void AddContactCommandAction()
        {
            if (Success)
            {
                _navigationService.GoBack();
                return;
            }
            _isBusy = true;
            AddContactCommand.RaiseCanExecuteChanged();
            ChatMessage msg = new ChatMessage(_currentClient.CurrentUserInfo.ID, _currentClient.CurrentUserInfo.UserName, MessageType.SendFriendRequest, this.MessageToReceiverText, this.InputText);

            StatusText = string.Empty;
            DatabaseQueryResponse response = await _currentClient.Connection.SendQuery(msg);
            this.Success = response.Success;
            this.StatusText = response.StatusText;
            if (response.Success == true)
            {
                NextButtonText = "Done";
            }
            _isBusy = false;
            AddContactCommand.RaiseCanExecuteChanged();
        }
    }
}